package com.liu.tools;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.thoughtworks.xstream.XStream;

public class XmlUtil {

	/**
	 * @DateTime 2015年12月28日下午3:05:03
	 * @Author 刘兴密
	 * @QQ 63972012
	 * @Desc 将xml数据转换为对象
	 * @param alias
	 * @param xml
	 * @param tClass
	 * @return  Object
	 */
	public static Object getObjectFromXML(String alias, String xml, Class<?> tClass) {
        //将从API返回的XML数据映射到Java对象
        XStream xStreamForResponseData = new XStream();
        xStreamForResponseData.alias(alias, tClass);
        xStreamForResponseData.ignoreUnknownElements();//暂时忽略掉一些新增的字段
        return xStreamForResponseData.fromXML(xml);
    }
	
	
	public static Object XMLStringToBean(String xml, Class<?> tClass){  
        try {  
            JAXBContext context = JAXBContext.newInstance(tClass);  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            
            Object object = unmarshaller.unmarshal(new StringReader(xml));  
            return object;
        } catch (JAXBException e) {  
            e.printStackTrace();  
            return null;
        }  
          
    } 
	
	
	public static Map<String,Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException {

	        //这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
	        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder = factory.newDocumentBuilder();
	        InputStream is =  getStringStream(xmlString);
	        Document document = builder.parse(is);

	        //获取到document里面的全部结点
	        NodeList allNodes = document.getFirstChild().getChildNodes();
	        Node node;
	        Map<String, Object> map = new HashMap<String, Object>();
	        int i=0;
	        while (i < allNodes.getLength()) {
	            node = allNodes.item(i);
	            if(node instanceof Element){
	                map.put(node.getNodeName(),node.getTextContent());
	            }
	            i++;
	        }
	        return map;

	    }
	
	  public static InputStream getStringStream(String sInputString) {
	        ByteArrayInputStream tInputStringStream = null;
	        if (sInputString != null && !sInputString.trim().equals("")) {
	            tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
	        }
	        return tInputStringStream;
	  }

}
